package com.itlong.cloud.network.tcp.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;

/**
 * <desc>
 *      客户端连接管理
 * </desc>
 *
 * @createDate 2018/10/30
 */
public class ChannelPoolManage {

    //客户端连接通道管理map
    private static Map<String , SocketChannel> map = new ConcurrentHashMap<>();
    //用于云端同步指令下发时使用,客户端key：同步锁 一 一对应
    private static Map<String,Lock> channelLockMap = new ConcurrentHashMap<>();

    /**
     * <desc>
     *      删除指定的通道
     * </desc>
     *
     * @param channel 服务通道
     * @author Wenchao.L
     * @createDate 2018/11/1
     */
    public static void remove(SocketChannel channel){
        for (Map.Entry<String,SocketChannel> entry:map.entrySet()){
            if (entry.getValue()==channel){
                map.remove(entry.getKey());
            }
        }
    }

    /**
     * <desc>
     *      获取所有注册的通道
     * </desc>
     *
     * @author Wenchao.L
     * @createDate 2018/11/1
     */
    public static List<SocketChannel> getChannels() {
        List<SocketChannel> channels = new ArrayList<>();
        Set<String> keys = map.keySet();
        for (String key : keys) {
            channels.add( map.get(key));
        }
        return channels;
    }

    /**
     * <desc>
     *      获取所有存活的客户端列表
     * </desc>
     *
     * @author Wenchao.L
     * @createDate 2019/4/3
     */
    public static List<String> getDevices() {
        List<String> channels = new ArrayList<>();
        Set<String> keys = map.keySet();
        for (String key : keys) {
            channels.add(key);
        }
        return channels;
    }



    public static void add(String clientId,SocketChannel channel){
        map.put(clientId, channel);
    }

    public static Channel get(String clientId){
        return map.get(clientId);
    }


    public static void setChannelLock(String key,Lock lock){
        channelLockMap.put(key,lock);
    }

    public static Lock getChannelLock(String key){
        return channelLockMap.get(key);
    }



}
